<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.query.name"
        placeholder="评审名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="filter"
      />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="filter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="id" align="center" label="ID" width="80" sortable>
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="评审名称" sortable align="center">
        <template v-slot="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="passRate" label="通过率" sortable align="center" width="90">
        <template v-slot="{row}">
          {{ row.passRate }}%
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" sortable align="center" width="110px">
        <template v-slot="{row}">
          <el-tag v-if="row.status === 0" type="default">none</el-tag>
          <el-tag v-else-if="row.status === 2" type="info">等待评审</el-tag>
          <el-tag v-else-if="row.status === 3" type="danger">评审不通过</el-tag>
          <el-tag v-else-if="row.status === 4" type="success">评审通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="initiatorUserId" label="发起人" align="center" width="80">
        <template v-slot="{row}">
          {{ selectName(row.initiatorUserId) }}
        </template>
      </el-table-column>
      <el-table-column label="已评" align="center" width="80">
        <template v-slot="{row}">
          {{ `${row.reviewers} / ${row.totalReviewers}` }}
        </template>
      </el-table-column>
      <el-table-column label="评审时间" width="180" align="center">
        <template v-slot="{row}">
          <span> {{ row.startedAt | parseTime('{y}-{m}-{d}') }} </span> / <span> {{ row.endedAt | parseTime('{y}-{m}-{d}') }} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="450">
        <template v-slot="{row, $index}">
          <el-button icon="el-icon-caret-right" type="primary" size="mini" @click="handleRun(row)">开始</el-button>
          <el-button type="info" size="mini" :disabled="row.status===4" @click="stop(row)"><svg-icon icon-class="stop" /> 结束</el-button>
          <el-button icon="el-icon-edit" type="info" size="mini" :disabled="row.status===4" @click="handleUpdate(row)">编辑</el-button>
          <el-button icon="el-icon-plus" type="primary" size="mini" :disabled="row.status===4" @click="handleAdd(row)">添加用例</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" :disabled="row.status===4" @click="del(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="listQuery.totalRecords>0"
      :total="listQuery.totalRecords"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="100px">
        <el-form-item label="评审名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入评审名称" />
        </el-form-item>
        <el-form-item label="评审用户:" prop="user">
          <el-select
            v-model="form.user"
            value-key="id"
            style="width: 100%"
            clearable
            filterable
            multiple
            placeholder="请选择评审人"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:" prop="startedAt">
          <el-date-picker
            v-model="form.startedAt"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="结束时间:" prop="endedAt">
          <el-date-picker
            v-model="form.endedAt"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, del, add, update, findById, stop } from '@/api/functional_test/test_case_manage/review'
import Pagination from '@/components/Pagination'
import { selectUserByProjectId } from '@/api/user'

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    caseType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      projectId: this.$store.getters.projectId,
      list: null,
      listLoading: true,
      userOptions: [],
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
          projectId: this.$store.getters.projectId
        }
      },
      form: {
        id: undefined,
        name: '',
        passRate: '',
        status: '',
        initiatorUserId: '',
        reviewers: '',
        startedAt: '',
        endedAt: '',
        totalReviewers: '',
        projectId: this.$store.getters.projectId
      },
      dialogFormVisible: false,
      isCreate: !this.$route.query.suitID,
      formLabelWidth: '120px',
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      robotListData: [],
      rules: {
        name: [
          { required: true, message: '请输入计划名称', trigger: 'change' },
          { max: 50, message: '计划名称 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        user: [{ required: true, message: '请选择评审用户', trigger: 'change' }],
        startedAt: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
        endedAt: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchData()
    this.selectUserByProjectId()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    create() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.projectId = this.$store.getters.projectId
          add(this.form).then(response => {
            this.dialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.form)
          update(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.form.id)
            this.fetchData()
            this.list.splice(index, 1, this.form)
            this.dialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        startedAt: '',
        endedAt: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAdd(row) {
      this.form = Object.assign({}, row)
      this.$router.push({ path: '/functional_test/edit_review', query: { reviewId: row.id, caseType: 1 }})
    },
    handleUpdate(row) {
      this.form = Object.assign({}, row) // 复制行数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.findById()
    },
    selectUserByProjectId() { // 通过 projectId 查询对应的 user 信息
      selectUserByProjectId(this.listQuery.query.projectId).then(response => {
        this.userOptions = response.data // 将后端返回的值赋给 userOptions 列表
      })
    },
    findById() {
      if (this.form.id) {
        findById(this.form.id).then(response => {
          this.form.user = response.data.user
        })
      }
    },
    handleRun(row) {
      this.$router.push({ path: '/functional_test/review_execute', query: { id: row.id }})
    },
    del(row, index) {
      this.$confirm('是否删除此记录?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.list.splice(index, 1)
          this.fetchData()
        })
      })
    },
    selectName(uid) { // 根据 uid 转成用户名称
      for (const user of this.userOptions) { // 遍历 userOptions 这个数组 拿到每一组对象
        if (user.id === uid) { // 每一组对象中的 ID 和 uid 进行匹配
          return user.name // 如果匹配，说明找到对应的用户
        }
      }
      return '' // 如果遍历完还没有找到，说明该用户不存在
    },
    stop(row) {
      this.$confirm('当前共需 ' + row.totalReviewers + ' 人评审已评' + row.reviewers + ' 人，结束评审后将无法继续评审，请确认？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        stop(row.id).then(response => {
          row.status = 4
          this.$message({ message: '结束评审成功！', type: 'success' })
        })
      }).catch(() => {
      })
    }
  }
}
</script>
